Supply Chain Chaos 📉
Ships are arriving in a scrambled order. We need to calculate the Chaos Metric (number of inversions) to optimize the AI traffic controller.
What is an Inversion?
A pair of indices $(i, j)$ is an inversion if:
- $i < j$ (Ship $i$ arrives before $j$)
- $A[i] > A[j]$ (Ship $i$ has higher priority ID)
Analysis 🔍
Example Sequence: [2, 4, 1, 3, 5]
- ❌ (2, 1): 2 comes before 1, but 2 > 1
- ❌ (4, 1): 4 comes before 1, but 4 > 1
- ❌ (4, 3): 4 comes before 3, but 4 > 3
- Total Chaos: 3 Inversions
The Challenge
A brute force nested loop is $O(N^2)$.
for i in range(n):
for j in range(i+1, n): ...
for j in range(i+1, n): ...
For $N=100,000$, this takes ~10 billion ops. Result: Time Limit Exceeded.